﻿using WCS.Entities;

namespace WCS.Services
{
    public delegate Task FilterDelegate(FilterContext context);
    public class JobFilterBuilder : IFilterBuilder
    {
        private readonly IList<Func<FilterDelegate, FilterDelegate>> _middlewares = new List<Func<FilterDelegate, FilterDelegate>>();
        public FilterDelegate Build()
        {
            FilterDelegate app = context =>
            {
                return Task.CompletedTask;
            };

            for (var c = _middlewares.Count - 1; c >= 0; c--)
            {
                app = _middlewares[c](app);
            }

            return app;
        }

        public IFilterBuilder New()
        {
            return new JobFilterBuilder();
        }

        public IFilterBuilder Use(Func<FilterDelegate, FilterDelegate> middleware)
        {
            _middlewares.Add(middleware);
            return this;
        }
    }

    public interface IFilterBuilder
    {
        IFilterBuilder Use(Func<FilterDelegate, FilterDelegate> middleware);

        FilterDelegate Build();

        IFilterBuilder New();

    }


    public static class UseExtensions
    {

        public static IFilterBuilder Use(this IFilterBuilder app, Func<FilterContext, Func<Task>, Task> middleware)
        {
            return app.Use(next =>
            {
                return context =>
                {
                    Func<Task> simpleNext = () => next(context);
                    return middleware(context, simpleNext);
                };
            });
        }


    }

}
